package com.zjt.web.api;

import com.zjt.dao.product.IQrCodeDao;
import com.zjt.entity.Record;
import com.zjt.entity.brandcategory.Brand;
import com.zjt.entity.factory.FactoryInfo;
import com.zjt.entity.product.ProductInfo;
import com.zjt.entity.resource.ProductResource;
import com.zjt.service.IFactoryService;
import com.zjt.service.IStaticParameterService;
import com.zjt.service.product.IBrandCategoryService;
import com.zjt.service.product.IProductService;
import com.zjt.service.user.IClientUserService;
import com.zjt.service.user.IRecordService;
import com.zjt.utils.DateUtil;
import com.zjt.utils.StringUtil;
import com.zjt.web.api.vo.base.PageVO;
import com.zjt.web.api.vo.base.RecordVO;
import com.zjt.web.api.vo.base.SecurityVO;
import com.zjt.web.api.vo.base.StateVO;
import com.zjt.web.api.vo.request.HistoryReqVO;
import com.zjt.web.api.vo.request.KnowledgeReqVO;
import com.zjt.web.api.vo.response.HistoryRespVO;
import com.zjt.web.api.vo.response.KnowledgeRespVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: xueyanbeijing
 * Date: 12-8-14
 * Time: AM10:51
 * 历史记录接口
 */

@Controller
@RequestMapping(value = "/api/history")
public class HistoryAPIController {
    private static Logger logger = LoggerFactory.getLogger(HistoryAPIController.class);
    private static String codeTypeBarCode = "barcode";
    private String baseProductUrl = "";
    private static String codeTypeQrCode = "qrcode";
    private IClientUserService clientUserService;
    private IRecordService recordService;
    private IProductService productService;
    private IQrCodeDao qrCodeDao;
    private IBrandCategoryService brandCategoryService;
    private IFactoryService factoryService;
    private IStaticParameterService staticParameterService;

    @Autowired
    public void setStaticParameterService(IStaticParameterService staticParameterService) {
        this.staticParameterService = staticParameterService;
    }

    @Autowired
    public void setFactoryService(IFactoryService factoryService) {
        this.factoryService = factoryService;
    }

    @Autowired
    public void setBrandCategoryService(IBrandCategoryService brandCategoryService) {
        this.brandCategoryService = brandCategoryService;
    }


    @Autowired
    public void setClientUserService(IClientUserService clientUserService) {
        this.clientUserService = clientUserService;
    }
    @Autowired
    public void setRecordService(IRecordService recordService) {
        this.recordService = recordService;
    }

    @Autowired
    public void setProductService(IProductService productService) {
        this.productService = productService;
    }

    @Autowired
    public void setQrCodeDao(IQrCodeDao qrCodeDao) {
        this.qrCodeDao = qrCodeDao;
    }

    private void loadProductImageUrl(String paramterName)
    {
        try
        {
            baseProductUrl = this.staticParameterService.getParameterValueByName(paramterName).trim();
        }catch (Exception e){
            logger.error("取常量表异常");
        }
    }
    /**
     * 最新扫描记录列，所有用户。
     * 启动时载入扫描记录列表。
     * historyReqVO中无须带有UserId值，可以分页载入，例如apple默认滑动载入下一页。
     * @return
     */
    @RequestMapping(value = {"lastedList.json", ""})
    @ResponseBody
    private  HistoryRespVO lastedList(HistoryReqVO historyReqVO)
    {
        logger.info("/api/history/lastedList request parms = " + historyReqVO.toString());
        //TODO 进行请求参数的解析
        StateVO stateVO = new StateVO();
        List<RecordVO> recordVOList = new ArrayList<RecordVO>();
        PageVO pageVO = new PageVO();
        pageVO.setPageNo(historyReqVO.getPageNo());
        this.loadProductImageUrl("productImageUrl");   //取默认目录
        try
        {
                pageVO.setPageNo(historyReqVO.getPageNo());
                List<Record> list = this.recordService.getRecordListByUserId(0,pageVO);
                if (list!=null&&list.size()>0)
                {
                    for (Record record:list)
                    {
                        RecordVO recordVO = new RecordVO();
                        ProductInfo productInfo = null;
                        long productId = -1;
                        String brandName = "";
                        try
                        {
                            //  record 扫描时，会在记录中存储productid  如果库中没有此产品，productId为-1
                            if (record.getProductId()!=-1)
                            {
                                productId = record.getProductId();
                                productInfo = this.productService.getProductInfoById(productId);
                            }
                        }
                        catch (Exception e1){
                            logger.error("productInfo exception productInfo="+e1.getStackTrace().toString());
                        }
                        String goodsPicUrl=null,goodsBigPicUrl=null,goodDesc = "",goodsTitle="";// 默认的白图片

                        long searchNum = 0;//客户端只有条形码才会显示此数据
                        //searchNum = this.recordService.countRecordByCodeValue(record.getCodeValue());//还有点点问题，未实现不同的产品不同的计数
                        if (productInfo!=null)
                        {
                            productId = productInfo.getId();
                            Brand tempBrand = null;
                            if (productInfo.getBrandId()>0)
                            {
                                tempBrand = this.brandCategoryService.getBrandById(productInfo.getBrandId());
                                brandName = tempBrand.getChName();
                            }
                            //TODO 小图与大图的地址获取：
                            if (productInfo.getSmallPicture()!=null&&productInfo.getSmallPicture().length()>0)
                            {
                                goodsPicUrl = productInfo.getSmallPicture();   //还未完成，需要建立一个函数，形成文件名在后面增加一个big  small等。
                                goodsPicUrl = baseProductUrl + goodsPicUrl;
                            }
                            if (productInfo.getBigPicture()!=null&&productInfo.getBigPicture().length()>0)
                            {
                                goodsBigPicUrl = productInfo.getBigPicture();
                                goodsBigPicUrl = baseProductUrl  + goodsBigPicUrl;
                            }

                            //TODO  如果productInfo.getDescription() 不存在，则取 企业相关信息作为描述：
                            //第一行
                            if (productInfo.getItemName()!=null&&productInfo.getItemName().trim().length()>0)
                                goodsTitle = StringUtil.subString(productInfo.getItemName(),13) +"\n";
                            else
                            if (record.getCodeType().equalsIgnoreCase(codeTypeBarCode))
                                goodsTitle = productInfo.getCodeValue()+"\n";

                            FactoryInfo tempFactoryInfo = null;
                            if (tempBrand!=null&&tempBrand.getFactoryId()>0)//确保商标存在。
                            {
                                if(brandName!=null&&brandName.length()>0)
                                    goodDesc = "商标:" +brandName+"\n";//商标
                                tempFactoryInfo = this.factoryService.getFactoryInfoById(tempBrand.getFactoryId());
                                if (tempFactoryInfo!=null)
                                    //第二行
                                    goodsTitle = goodsTitle + StringUtil.subString(tempFactoryInfo.getChName(), 13) +"\n";
                            }

                            if (productInfo.getSpecification()!=null&&productInfo.getSpecification().trim().length()>0)
                                goodDesc = goodDesc + "规格:" +productInfo.getSpecification()+"\n";
                            if (productInfo.getShortDescription()!=null&&productInfo.getShortDescription().trim().length()>0)
                                goodDesc = goodDesc + "描述:" +productInfo.getShortDescription()+"\n";
                            if (tempFactoryInfo!=null)
                                goodDesc = goodDesc + "地址:" + tempFactoryInfo.getAddress();


                        } else  //productId == -1  产品不存在。
                        {
                            if (record.getCodeType().equalsIgnoreCase(codeTypeBarCode))
                                goodsTitle = "条码:"+record.getCodeValue();
                            else
                                goodsTitle = "暂未收录产品信息";
                        }
                        recordVO.setGoodsBigPicUrl(goodsBigPicUrl);
                        recordVO.setGoodsDesc(goodDesc);
                        recordVO.setGoodsPicUrl(goodsPicUrl);
                        recordVO.setGoodsReal(record.getGoodsReal());
                        recordVO.setGoodsTitle(goodsTitle);
                        recordVO.setRecordId(record.getId());
                        recordVO.setSearchNum(searchNum);
                        recordVO.setCodeType(record.getCodeType());
                        recordVO.setFirstSearchTime(DateUtil.getDayStr(record.getUpdateDate(), "yyyy-MM-dd HH:mm:ss"));
                        recordVO.setProductId(productId);
                        recordVO.setCodeValue(record.getCodeValue());
                        recordVOList.add(recordVO);
                    }
                }
        }catch (Exception e){
            logger.error("封装VO 历史记录vo exception "+e);
        }
        HistoryRespVO historyRespVO = new HistoryRespVO();
        //TODO 进行业务逻辑的处理 ， 封装应答数据
        historyRespVO.setStateVO(stateVO);
        historyRespVO.setRecordVOList(recordVOList);
        historyRespVO.setPageVO(pageVO);

        logger.info("/api/history/lastedList response result = " + historyRespVO.getRecordVOList().size());
        return historyRespVO;
    }

    /**
     * 历史记录列表
     *
     * @param historyReqVO
     * @return
     */
    @RequestMapping(value = {"list.json", ""})
    @ResponseBody
    public HistoryRespVO list(HistoryReqVO historyReqVO) {
        logger.info("/api/history/list request parms = " + historyReqVO.toString());
        //TODO 进行请求参数的解析
        StateVO stateVO = new StateVO();
        List<RecordVO> recordVOList = new ArrayList<RecordVO>();
        PageVO pageVO = new PageVO();
        pageVO.setPageNo(historyReqVO.getPageNo());
        this.loadProductImageUrl("productImageUrl");   //取默认目录
        try
        {
            boolean userExist = false;
            userExist = this.clientUserService.checkExistByUserId(historyReqVO.getUserId());
            if (userExist==true)
            {
                pageVO.setPageNo(historyReqVO.getPageNo());
                List<Record> list = this.recordService.getRecordListByUserId(historyReqVO.getUserId(),pageVO);
                if (list!=null&&list.size()>0)
                {
                    for (Record record:list)
                    {
                        RecordVO recordVO = new RecordVO();
                        ProductInfo productInfo = null;
                        ProductResource productResource = null;
                        long productId = -1;
                        String brandName = "";
                        try
                        {
                            if (record.getProductId()!=-1)
                            {
                                productId = record.getProductId();
                                productInfo = this.productService.getProductInfoById(productId);
                            }
                        }
                        catch (Exception e1){
                            logger.info("取扫描的产品异常:");
                        }

                        String goodsPicUrl=null,goodsBigPicUrl=null,goodDesc = "",goodsTitle="";// 默认的白图片
                        long searchNum = 0;
                        //searchNum = this.recordService.countRecordByCodeValue(record.getCodeValue());//还有点点问题，未实现不同的产品不同的计数
                        if (productInfo!=null)
                        {
                            productId = productInfo.getId();
                            Brand tempBrand = null;
                            if (productInfo.getBrandId()>0)
                            {
                                tempBrand = this.brandCategoryService.getBrandById(productInfo.getBrandId());
                                brandName = tempBrand.getChName();
                            }


                            //TODO 小图与大图的地址获取：
                            if (productInfo.getSmallPicture()!=null&&productInfo.getSmallPicture().length()>0)
                            {
                                goodsPicUrl = productInfo.getSmallPicture();   //还未完成，需要建立一个函数，形成文件名在后面增加一个big  small等。
                                goodsPicUrl = baseProductUrl + goodsPicUrl;
                            }
                            if (productInfo.getBigPicture()!=null&&productInfo.getBigPicture().length()>0)
                            {
                                goodsBigPicUrl = productInfo.getBigPicture();
                                goodsBigPicUrl = baseProductUrl  + goodsBigPicUrl;
                            }

                            //TODO  如果productInfo.getDescription() 不存在，则取 企业相关信息作为描述：

                            //第一行
                            if (productInfo.getItemName()!=null&&productInfo.getItemName().trim().length()>0)
                                goodsTitle = StringUtil.subString(productInfo.getItemName(),13)+"\n";
                            else if (record.getCodeType().equalsIgnoreCase(codeTypeBarCode))
                                goodsTitle = "条码:"+productInfo.getCodeValue()+"\n";

                            FactoryInfo tempFactoryInfo = null;
                            if (tempBrand!=null&&tempBrand.getFactoryId()>0)//确保商标存在。
                            {
                                if(brandName!=null&&brandName.length()>0)
                                    goodDesc = "商标:" +brandName+"\n";//商标
                                tempFactoryInfo = this.factoryService.getFactoryInfoById(tempBrand.getFactoryId());
                                if (tempFactoryInfo!=null)
                                    //第二行
                                    goodsTitle = goodsTitle +  StringUtil.subString(tempFactoryInfo.getChName(), 13)+"\n";
                            }

                            if (productInfo.getSpecification()!=null&&productInfo.getSpecification().trim().length()>0)
                                goodDesc = goodDesc + "规格:" +productInfo.getSpecification()+"\n";
                            if (productInfo.getShortDescription()!=null&&productInfo.getShortDescription().trim().length()>0)
                                goodDesc = goodDesc + "描述:" +productInfo.getShortDescription()+"\n";
                            if (tempFactoryInfo!=null)
                                goodDesc = goodDesc + "地址:" + tempFactoryInfo.getAddress();

                        } else  //productId == -1  产品不存在。
                        {
                            if (record.getCodeType().equalsIgnoreCase(codeTypeBarCode))
                                goodsTitle = "条码:"+record.getCodeValue();
                            else
                                goodsTitle = "暂未收录产品信息";
                        }

                        recordVO.setGoodsBigPicUrl(goodsBigPicUrl);
                        recordVO.setGoodsDesc(goodDesc);
                        recordVO.setGoodsPicUrl(goodsPicUrl);
                        recordVO.setGoodsReal(record.getGoodsReal());
                        recordVO.setGoodsTitle(goodsTitle);
                        recordVO.setRecordId(record.getId());
                        recordVO.setSearchNum(searchNum);
                        recordVO.setCodeType(record.getCodeType());
                        recordVO.setFirstSearchTime(DateUtil.getDayStr(record.getUpdateDate(), "yyyy-MM-dd HH:mm:ss"));
                        recordVO.setProductId(productId);
                        recordVO.setCodeValue(record.getCodeValue());
                        recordVOList.add(recordVO);
                    }
                }
            }else
            {
                stateVO.setCode(-1);
                stateVO.setMsg("client userId 不存在");
            }
        }catch (Exception e){
            logger.info("list exception recordVOList=");
        }
        HistoryRespVO historyRespVO = new HistoryRespVO();
        //TODO 进行业务逻辑的处理 ， 封装应答数据
        historyRespVO.setStateVO(stateVO);
        historyRespVO.setRecordVOList(recordVOList);
        historyRespVO.setPageVO(pageVO);

        logger.info("/api/history/list response result = " + historyRespVO.getRecordVOList().size());
        return historyRespVO;
    }
    /**
     * 取单个历史记录的防伪记录
     *
     * @param knowledgeReqVO
     * @return
     */
    @RequestMapping(value = {"loadKnowledge.json", ""})
    @ResponseBody
    public KnowledgeRespVO loadKnowledge(KnowledgeReqVO knowledgeReqVO)
    {
        logger.info("/api/history/loadKnowledge request parms = " + knowledgeReqVO.toString());
       try
       {
           Record record = null;
           record = this.recordService.getRecordById(knowledgeReqVO.getRecordId());
           if (record!=null)
           {
               long productId = -1;
               ProductInfo productInfo = null;
               if (record.getCodeType().equalsIgnoreCase("barcode"))//如果是条码
                   productInfo = this.productService.getProductInfoByBarCode(record.getCodeValue());
               else
                   productInfo = this.productService.getProductInfoById(record.getProductId());

               logger.info("取得需要取得防伪知识的产品表：productInfo="+productInfo.toString());
               //TODO 需要建立防伪知识信息表与产品关联表       未完成
               //this.knowledgeService.getKnowledgeListByProductId(productId);
           }
       }catch (Exception e){}
       String knowledgeString = "";
      //TODO 构造返回对像
        StateVO stateVO = new StateVO();
        SecurityVO securityVO = new SecurityVO();
        knowledgeString= "商品知识\n" +
                "\n" +
                "　　冷却肉指严格执行兽医卫生检疫制度下屠宰后的畜胴体迅速进行冷却处理，使胴体温度在24小时内降为0～4℃，并在后续加工、流通和销售过程中始终保持0～4℃的生鲜肉，也有人称之为预冷肉或排酸肉。\n" +
                "\n" +
                "　　冷却肉的加工是在正常屠宰后畜胴体迅速进行冷却处理，冷却可以是一段进行，也可分为两段进行。一段进行即始终在0～4℃下进行;两段冷却是先在-10℃以下冷却1～2小时，然后在0～4℃下冷却，使胴体的中心温度达到0～4℃。冷却效果两段为好。由于冷却肉经过充分的解僵成熟过程，所以肉质柔软有弹性，滋味鲜美，汁液流失少，避免了营养成分的损失，比热鲜肉和冷冻肉更适合家庭烹调和肉制品加工。热鲜肉由于基本未经过解僵成熟过程，在僵直期内煮不烂，味道不好。冷冻肉对于畜禽肉的保鲜起到了很好的作用，但由于在冻结过程中会破坏肉的细胞。在解冻时会产生汁液流失，同时带走了部分营养。一般冻结方法汁液流失达5%～7%，所以经过冻结的肉口味不如冷却肉。\n" +
                "\n" +
                "　　冷却肉由于在分割、加工、流通和销售过程中始终处于低温控制中，大多数微生物的生长繁殖受到抑制，一些病源菌分泌毒素的速度大大降低，甚至被抑制，所以冷却肉的安全性比较有保证。\n" +
                "\n" +
                "　　冷却肉产品一般都以分割肉小包装的形式出现在较大型的有专用冷藏柜销售的超市商场，农贸市场出售的肉均为热鲜肉和冷冻肉。\n" +
                "\n" +
                "　　冷却肉生产一般都是比较大型屠宰企业，整个过程都有较好的卫生管理，屠宰加工时肉的初始菌含量少，加上合理的包装，并严格控制运输、销售过程中的温度，这样使冷却肉的货架期达到15天以上。在销售过程中，由于肌红蛋白被氧化，使鲜红色变为暗红色或褐色，这是正常的颜色变化，不影响肉的内在质量。\n" +
                "\n" +
                "　　质量要求与技术标准\n" +
                "\n" +
                "　　目前，国内外对肉的卫生和安全都很重视，对肉的新鲜度和含菌量制定标准进行限制，如德国将冷却肉的含菌量限定为5.0×106个/克，当肉的含菌量小于5.5×106个/克时为合格，亮绿灯，含菌量等于5.0×106个/克时为可以接受，亮黄灯，含菌量大于5.0×106个/克时不可食用，亮红灯。我国国家标准GB18406.3-2001《无公害畜禽肉》中规定：鲜畜禽肉菌落总数不高于1.0×106个/克，大肠菌群不高于1.0×104个/100克;冻畜禽肉菌落总数不高于5.0×105个/克，大肠菌不高于1.0×103个/100克，均高于国际上一些国家的同类标准。同时国家标准GB9959.1-2001《鲜、冻片猪肉》中规定：肉的新鲜度挥发性盐基氮≤20毫克/100克;含水量≤77%。" ;
        securityVO.setSecurityCode(true);
        securityVO.setKnowledge(knowledgeString);
        KnowledgeRespVO knowledgeRespVO = new KnowledgeRespVO();
        knowledgeRespVO.setStateVO(stateVO);
        knowledgeRespVO.setSecurityVO(securityVO);
        logger.info("/api/history/loadKnowledge response result = knowledgeRespVO.toString().length()=" + knowledgeRespVO.toString().length());
        return knowledgeRespVO;
    }
}
